﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Growatt.Component.Cls;
using static Growatt.CreateXLXFormWord.ShinebusUploadRecordFeishuModel;
using Growatt.DuiHelpers;
using Growatt.ShinebusService.Model;
using Growatt.ShinebusServiceUploadPack.Service.FeishuHelper;

namespace Growatt.CreateXLXFormWord
{
    public class ShinebusUploadRecordFeishu
    {
        private string baseID = "FpsPbeuX5aJpM8s7kB4c4U5SnJd";
        private string tablesID = "tbl2r2Tccfgmdq7B";
        public string accessToken = "t-e13d5ec1954e82e458f3ce04491c54ea8c9abcef";

        public ShinebusUploadRecordFeishu(string baseID, string tablesID, string accessToken)
        {
            this.baseID = baseID;
            this.tablesID = tablesID;
            this.accessToken = accessToken;
        }



        public class ShinebusUploadRecordBody
        {
            public UpdateFields fields { get; set; }
        }
        /// <summary>
        /// 获取登录时间
        /// </summary>
        /// <param name="recordBody"></param>
        public async Task<FirmwareUploadInfoResponse> InsertServerAsync22(RecordFieldsFileUploadUtilsBody recordBody,
            string searchKey, string fileToken,
            string baseID,
            string tablesID,
            string accessToken,
            string ViewId)
        {
            searchKey = System.IO.Path.GetFileName(searchKey);
            var Body = string.Empty;
            var listVersionRecord = await SearchServerAsync(baseID, tablesID, this.accessToken, ViewId);
            if (listVersionRecord == null)
                return new FirmwareUploadInfoResponse() { UploadStatus = -1, Message = "无法获取指定版本" };
            var list = listVersionRecord.Where(o => o.fields.升级后目标版本 != null).ToList().Select(o => o.fields.升级后目标版本.FirstOrDefault().text);
          
            return new FirmwareUploadInfoResponse() { UploadStatus = 0, Message = "无法获取指定版本" };

        }
        /// <summary>
        /// 获取登录时间
        /// </summary>
        /// <param name="recordBody"></param>
        public async Task<FirmwareUploadInfoResponse> InsertServerAsync(RecordFieldsFileUploadUtilsBody recordBody, 
            string searchKey, string fileToken,
            string baseID,
            string tablesID, 
            string accessToken,
            string ViewId)
        {
            searchKey = System.IO.Path.GetFileName(searchKey);
            var Body = string.Empty;
            var listVersionRecord = await SearchServerAsync( baseID,  tablesID, this.accessToken, ViewId);
            if (listVersionRecord == null)
                return new FirmwareUploadInfoResponse() { UploadStatus = -1, Message = "无法获取指定版本" };
            var list = listVersionRecord.Where(o => o.fields.升级后目标版本 != null).ToList().Select(o=>o.fields.升级后目标版本.FirstOrDefault().text);
            if (!list.Contains(searchKey)) //新增
            {
                return new FirmwareUploadInfoResponse() { UploadStatus = 0, Message = $"无法获取指定版本:{searchKey}" };
                #region 判断是否新增
                //FileUploadUtils fileUploadUtils = new FileUploadUtils(baseID, tablesID, this.accessToken);//更新表格ID
                //var to = recordBody.fields.升级前运行版本.FirstOrDefault();//获取附件的token
                //if (to != null)
                //{
                //    await fileUploadUtils.InsertServerOnlyOneFileAsync(to.file_token, recordBody.fields);
                //    return new FirmwareUploadInfoResponse() { UploadStatus = 1, Message = "新增:上传飞书文档成功" };
                //}
                //await fileUploadUtils.upload_OnlyOneFileAsynchronous(FilePath, DuiHelpers.DuiHelperJson.ObjectToJson(recordBody)); 
                #endregion
            }
            else //更新
            {
                var itemData = listVersionRecord.Where(o => o.fields.升级后目标版本 != null).ToList().FirstOrDefault(o => o.fields.升级后目标版本.FirstOrDefault().text.Equals(searchKey));
                if (itemData != null)
                {
                    if (itemData.fields.设备型号 != null)
                    {
                        recordBody.fields.设备型号 = itemData.fields.设备型号;
                    }
                    var code = await UpdateServerAsync(recordBody, itemData.record_id, baseID, tablesID, this.accessToken);
                    if (code == -1)
                    {
                        Debug.WriteLine("更新失败");
                    }
                    else
                    {
                        return new FirmwareUploadInfoResponse() { UploadStatus = 1, Message = "更新:上传飞书文档成功"  };
                    }
                }


            }
            return new FirmwareUploadInfoResponse() { UploadStatus = 0, Message = "无法获取指定版本" };

        }
        public string CreateRequestBody(List<string> fieldNames, string viewId)
        {
            var requestBody = new
            {
                field_names = fieldNames,
                view_id = viewId
            };
            return JsonConvert.SerializeObject(requestBody);
        }

        public async Task<List<UplaodInfoItem>> SearchServerAsync(string baseID, string tablesID, string accessToken, string viewId)
        {
            var apiHelper = new FeishuAPIHelper();
            accessToken = await apiHelper.GetTenantAccessToken();
            if (string.IsNullOrEmpty(accessToken))
                return null;
            // 创建 HttpClient 实例
            using (var httpClient = new HttpClient())
            {
                // 设置请求头
                httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
                httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
                // 使用即将创建的方法构造请求体
                var fieldNames = typeof(UpdateFields).GetProperties().Select(o => o.Name).ToList();
                // 定义请求体
                var requestBody = new
                {
                    view_id = viewId
                };

                string jsonBody = DuiHelperJson.ObjectToJson(requestBody);

                // 创建请求内容
                var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");


                // 发送 POST 请求
                var url = $"https://open.feishu.cn/open-apis/bitable/v1/apps/{baseID}/tables/{tablesID}/records/search?page_size=2000&user_id_type=open_id";
                var response = await httpClient.PostAsync(url, content);

                // 确保请求成功
                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception("请求失败，状态码：" + response.StatusCode);
                }

                // 读取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();

                // 解析响应内容
                var jsonData = JsonConvert.DeserializeObject<UplaodInfoRootobject>(responseContent);

                // 返回结果
                return jsonData.data.items.ToList();
            }
        }

        public async Task<int> UpdateServerAsync(RecordFieldsFileUploadUtilsBody recordBody, string recordid, string baseID, string tablesID, string accessToken)
        {
            var apiHelper = new FeishuAPIHelper();
            accessToken = await apiHelper.GetTenantAccessToken();
            var jsonBody = JsonConvert.SerializeObject(recordBody);
            var client = new HttpClient();
            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Put,
                RequestUri = new Uri($"https://open.feishu.cn/open-apis/bitable/v1/apps/{baseID}/tables/{tablesID}/records/{recordid}"),
                Content = new StringContent(jsonBody, Encoding.UTF8, "application/json")
            };
            request.Headers.Add("Authorization", $"Bearer {accessToken}");

            var response = await client.SendAsync(request);
            var responseContent = await response.Content.ReadAsStringAsync();

            // 反序列化为对象
            var updateResponse = JsonConvert.DeserializeObject<UpdateResponse>(responseContent);
            if (updateResponse != null)
            {
                return updateResponse.code;
            }

            return -1;
        }

    }
}
